from rest_framework import viewsets
from .models import City, Datacenter, Host
from .serializers import CitySerializer, DatacenterSerializer, HostSerializer
import subprocess
from rest_framework.response import Response
from rest_framework.views import APIView


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class DatacenterViewSet(viewsets.ModelViewSet):
    queryset = Datacenter.objects.all()
    serializer_class = DatacenterSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer


class PingHostView(APIView):
    def get(self, request, hostname):
        try:
            result = subprocess.run(['ping',hostname], capture_output=True, text=True)
            if result.returncode == 0:
                return Response({"status": "success", "message": f"{hostname} is reachable"})
            else:
                return Response({"status": "error", "message": f"{hostname} is not reachable"})
        except:
            return Response({"status": "error", "message": "An error occurred while pinging the host"})
